<template>
  <div class="app-container">
    <div class="head-container">
      <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
        <el-form-item label="数据库名称" prop="databaseName">
          <el-input
            v-model="queryParams.databaseName"
            placeholder="请输入数据库名称"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="card-container">
      <el-button
        type="primary"
        icon="el-icon-plus"
        size="small"
        @click="handleAdd"
        v-hasPermi="['resource:database:add']"
      >新增</el-button>
      <el-button
        type="success"
        icon="el-icon-edit"
        size="small"
        @click="handleUpdate"
        :disabled="single"
        v-hasPermi="['resource:database:edit']"
      >修改</el-button>
      <el-button
        type="danger"
        icon="el-icon-delete"
        size="small"
        @click="handleDelete"
        :disabled="multiple"
        v-hasPermi="['resource:database:remove']"
      >删除</el-button>
      <el-button
        type="warning"
        icon="el-icon-download"
        size="small"
        @click="handleExport"
        v-hasPermi="['resource:database:export']"
      >导出</el-button>
    </div>

    <el-table
      v-loading="loading"
      :data="databaseProductList"
      @selection-change="handleSelectionChange"
      border
      fit
      stripe
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="产品ID" prop="productId" align="center" width="80" />
      <el-table-column label="数据库名称" prop="databaseName" align="center" />
      <el-table-column label="图标" prop="icon" align="center" width="100">
        <template slot-scope="scope">
          <img v-if="scope.row.icon" :src="scope.row.icon" class="table-img" />
        </template>
      </el-table-column>
      <el-table-column label="类型" prop="productType" align="center" />
      <el-table-column label="数据库描述" prop="description" align="center" :show-overflow-tooltip="true" />
      <el-table-column label="备注" prop="remark" align="center" />
      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
            v-hasPermi="['resource:database:edit']"
          />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="createTime" align="center" width="180" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['resource:database:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['resource:database:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改数据库产品对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="600px"
      append-to-body
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="数据库名称" prop="databaseName">
          <el-input v-model="form.databaseName" placeholder="请输入数据库名称" />
        </el-form-item>
        <el-form-item label="图标">
          <el-upload
            class="avatar-uploader"
            :action="'/common/upload'"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
            :before-upload="beforeUpload"
          >
            <img v-if="form.icon" :src="form.icon" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <div class="el-upload__tip">请上传大小不超过5MB格式为png/jpg/jpeg的文件</div>
        </el-form-item>
        <el-form-item label="类型" prop="productType">
          <el-checkbox-group v-model="typeOptions">
            <el-checkbox label="关系型" @change="updateProductType" />
            <el-checkbox label="非关系型" @change="updateProductType" />
            <el-checkbox label="单机" @change="updateProductType" />
            <el-checkbox label="分布式" @change="updateProductType" />
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="数据库描述" prop="description">
          <tinymce v-model="form.description" :height="200" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDatabaseProduct, getDatabaseProduct, addDatabaseProduct, updateDatabaseProduct, delDatabaseProduct, exportDatabaseProduct } from '@/api/resource/databaseProduct'

export default {
  name: 'DatabaseProduct',
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 数据库产品列表
      databaseProductList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        databaseName: '',
        productType: '',
        status: ''
      },
      // 表单参数
      form: {},
      // 类型选项
      typeOptions: [],
      // 表单校验
      rules: {
        databaseName: [
          { required: true, message: '数据库名称不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询数据库产品列表 */
    getList() {
      this.loading = true
      listDatabaseProduct(this.queryParams).then(response => {
        this.databaseProductList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$refs.queryForm.resetFields()
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.productId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加数据库产品'
      this.typeOptions = []
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const productId = row.productId || this.ids
      getDatabaseProduct(productId).then(response => {
        this.reset()
        this.form = response.data
        this.open = true
        this.title = '修改数据库产品'
        // 处理类型选项
        if (this.form.productType) {
          this.typeOptions = this.form.productType.split('-')
        } else {
          this.typeOptions = []
        }
      })
    },
    /** 状态改变 */
    handleStatusChange(row) {
      const status = row.status === '0' ? '1' : '0'
      this.$confirm('确认要修改该数据库产品的状态吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return updateDatabaseProduct({ productId: row.productId, status: status })
      }).then(() => {
        this.msgSuccess('修改成功')
      }).catch(() => {
        row.status = status
        this.msgError('修改失败')
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const productIds = row.productId || this.ids
      this.$confirm('确定要删除选中的数据库产品吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return delDatabaseProduct(productIds)
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      }).catch(() => {
        this.msgError('删除失败')
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('resource/database-product/export', {...this.queryParams}, `database-product_${new Date().getTime()}.xlsx`)
    },
    /** 表单重置 */
    reset() {
      this.form = {
        productId: null,
        databaseName: null,
        icon: null,
        productType: null,
        description: null,
        remark: null,
        status: '0'
      }
      this.resetForm('form')
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.form.productId != null) {
            updateDatabaseProduct(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess('修改成功')
                this.open = false
                this.getList()
              }
            })
          } else {
            addDatabaseProduct(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess('新增成功')
                this.open = false
                this.getList()
              }
            })
          }
        }
      })
    },
    /** 取消按钮 */
    cancel() {
      this.open = false
      this.reset()
    },
    /** 上传成功处理 */
    handleUploadSuccess(res, file) {
      this.form.icon = res.fileName
    },
    /** 上传前校验 */
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG/PNG 格式!')
      }
      if (!isLt5M) {
        this.$message.error('上传图片大小不能超过 5MB!')
      }
      return isJPG && isLt5M
    },
    /** 更新产品类型 */
    updateProductType() {
      this.form.productType = this.typeOptions.join('-')
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.head-container {
  margin-bottom: 16px;
}

.card-container {
  margin-bottom: 16px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #dcdfe6;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 150px;
  height: 150px;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #c0c4cc;
  width: 150px;
  height: 150px;
  line-height: 150px;
  text-align: center;
}

.avatar {
  width: 150px;
  height: 150px;
  display: block;
}

.table-img {
  width: 40px;
  height: 40px;
}
</style>